package org.vm.cmbcdirect.wechat.service;

import org.vm.cmbcdirect.wechat.model.resp.Article;
import org.vm.cmbcdirect.wechat.model.resp.NewsMessage;
import org.vm.cmbcdirect.wechat.model.resp.TextMessage;
import org.vm.cmbcdirect.wechat.utils.MessageUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by mv on 2016/3/22.
 *
 * 核心业务类
 */
public class CoreService {

    // 解析xml并返回信息
    public static String processRequest(HttpServletRequest request) {

        // 默认返回的文本消息内容
        String respContent = "请求处理异常，请稍候尝试！";

        // xml请求解析
        try {
            Map<String, String> requestMap = MessageUtil.parseXml(request);
            // 发送方帐号（open_id）
            String fromUserName = requestMap.get("FromUserName");
            // 公众帐号
            String toUserName = requestMap.get("ToUserName");
            // 消息类型
            String msgType = requestMap.get("MsgType");
            // 消息内容
            String content = requestMap.get("Content");

            // 文本消息
            if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
                return replyWithText(fromUserName, toUserName, respContent);
            }
            // 图片消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
                respContent = "images";
                return replyWithText(fromUserName, toUserName, respContent);
            }
            // 事件推送
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
                // 事件类型
                String eventType = requestMap.get("Event");
                // 订阅
                if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
                    return replyWithText(fromUserName, toUserName, "谢谢您的关注！");
                }
                // 自定义菜单点击事件
                else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
                    int eventKey = Integer.parseInt(requestMap.get("EventKey"));
                    switch (eventKey) {
                        case 11:
                            return replyWithPicAndText(
                                    fromUserName,
                                    toUserName,
                                    "共赢合作",
                                    "真诚欢迎您与我们合作",
                                    "http://mmbiz.qpic.cn/mmbiz/T1C9S5vpkvWxdKIY8Xx5TYVgZLe8BZElwG1ALYTDbAS4U8uxIS6CSwAR4a32szPF9v00jc4nAQaniayEaUzfJPA/640?wx_fmt=jpeg&tp=webp&wxfrom=5",
                                    "http://mp.weixin.qq.com/s?__biz=MzIzMDAxNDYwNQ==&mid=211054319&idx=1&sn=350055c7b6df2ae67fe5fe735fdd3f61#rd");
                        case 12:
                            return replyWithText(fromUserName, toUserName,
                                    "该功能尚未开通，请耐心等待。");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return respContent;
    }


    // 回复文字
    private static String replyWithText(String fromUserName, String toUserName,
                                        String respContent) {
        if (respContent == null)
            return null;
        TextMessage textMessage = new TextMessage();
        textMessage.setToUserName(fromUserName);
        textMessage.setFromUserName(toUserName);
        textMessage.setCreateTime(new Date().getTime());
        textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
        textMessage.setFuncFlag(0);
        textMessage.setContent(respContent);
        String respMessage = MessageUtil.textMessageToXml(textMessage);
        System.out.println("return: " + respMessage);
        return respMessage;
    }

    // 回复图文
    private static String replyWithPicAndText(String fromUserName,
                                              String toUserName, String title, String description, String picUrl,
                                              String contentUrl) {
        NewsMessage newsMessage = new NewsMessage();
        newsMessage.setToUserName(fromUserName);
        newsMessage.setFromUserName(toUserName);
        newsMessage.setCreateTime(new Date().getTime());
        newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
        newsMessage.setFuncFlag(0);
        List<Article> articleList = new ArrayList<Article>();
        Article article = new Article();
        article.setTitle(title);
        article.setDescription(description);
        article.setPicUrl(picUrl);
        article.setUrl(contentUrl);
        articleList.add(article);
        // 设置图文消息个数
        newsMessage.setArticleCount(articleList.size());
        // 设置图文消息包含的图文集合
        newsMessage.setArticles(articleList);
        // 将图文消息对象转换成xml字符串
        String respMessage = MessageUtil.newsMessageToXml(newsMessage);
        return respMessage;
    }
}
